<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\GroundChild;
use app\common\model\Ground;
use app\common\model\MoneyLog;
use app\common\model\DeviceOrder;
use fast\Random;
use think\Config;
use think\Db;
use think\Exception;
use think\Validate;
use app\common\model\User as UserModel;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third','sysProtocol'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 获取系统配置
     * @return void
     */
    public function sysConfig()
    {
        $site = $this->request->post('site');
        $config = config('site.'.$site);
        $this->success('ok',$config);
    }


    /**
     * 会员中心
     */
    public function index()
    {
        $user = $this->auth->getUserinfo();
        if($user['type'] > 0){
            //查询此商家所有场地
            $user_group = Ground::where('user_id',$this->auth->id)->column('id');
            //查询此商家所有场地
            $ground_ids = GroundChild::where('user_id',$this->auth->id)->column('ground_id');
            if(!$ground_ids){
                $ground_ids = [-1];
            }
            //获取所有设备
            if($this->auth->type != 0){
//                $ground_ids = GroundChild::where('user_id',$this->auth->id)->column('ground_id');
                $device = model('Device')->where('ground_id','in',array_merge($ground_ids,$user_group))->select();
            }else{
                $device = model('Device')->where('user_id',$user['id'])->select();
            }

            $deviceCount = array_count_values(array_column($device,'type'));
            $arr = [
                'all'=>count($device),
                'online'=>isset($deviceCount['online']) ? $deviceCount['online'] : 0,
                'offline'=>isset($deviceCount['offline']) ? $deviceCount['offline'] : 0,
                'all_faults'=>model('Device')->where('ground_id','in',array_merge($ground_ids,$user_group))->where('yj_status',3)->count(),
            ];
            $where = [];
            $where['device_order.ground_id'] = ['in',array_merge($ground_ids,$user_group)];
    //        $where['device.user_id'] = $this->auth->id;
//            $where['device_order.createtime'] = ['between', [strtotime(date('Y-m-d')), strtotime(date('Y-m-d').' 23:59:59')]];
            $where['device_order.is_gifts'] = 0;
            $where['device_order.status'] = 'paid';
            $today_order = DeviceOrder::with('device,ground')
            ->where($where)->whereTime('device_order.createtime','today')->count();
//            $user['today_order'] = MoneyLog::where('user_id',$user['id'])->where('device_id','>',0)->whereTime('createtime','today')->count();
            $user['today_order'] = $today_order;
            $user['today_income'] = MoneyLog::where('user_id',$user['id'])->where('device_id','>',0)->whereTime('createtime','today')->sum('money');

            //查询累计收益
            $user['total_income'] = MoneyLog::where('user_id',$user['id'])->where('device_id','>',0)->sum('money');
//            $user['total_order'] = MoneyLog::where('user_id',$user['id'])->where('device_id','>',0)->count();
            $user['total_order'] = DeviceOrder::with('device,ground')
            ->where($where)->count();
            $user['device_count'] = $arr;
        }
        $res = [
            'userinfo'=>$user
        ];
        $this->success('', $res);
    }

    //图片转base64
    public function img_base64($path){
        //对path进行判断，如果是本地文件就二进制读取并base64编码，如果是url,则返回
        $img_data="";
        if (substr($path,0,strlen("http")) === "http"){
            $img_data = $path;
        }else{
            if($fp = fopen($path, "rb", 0)) {
                $binary = fread($fp, filesize($path)); // 文件读取
                fclose($fp);
                $img_data = base64_encode($binary); // 转码
            }else{
                printf("%s 图片不存在",$path);
            }
        }
        return $img_data;
    }

    /**
     * 获取身份卡信息
     * @return void
     */
    public function getCardInfo()
    {
        $img = $this->request->post('img');
        $type = $this->request->post('type');
        $url = "https://cardnumber.market.alicloudapi.com/rest/160601/ocr/ocr_idcard.json";
        $appcode = "232ff63a9bea4c15911070485bfb52fe";
        $method = "POST";

        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/json; charset=UTF-8");

        //如果没有configure字段，config设为空
        $config = array(
            "side"=>$type,
            "configure"=>[
                "side"=>$type
            ]
        );

        $img_data=$this->img_base64($img);
        $request = array(
            "image" => "$img_data"
        );
        if(count($config) > 0){
            $request["configure"] = json_encode($config);
        }
        $body = json_encode($request);

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$".$url, "https://")){
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
        $result = curl_exec($curl);
        $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $rheader = substr($result, 0, $header_size);
        $rbody = substr($result, $header_size);

        // $httpCode = curl_getinfo($curl,CURLINFO_HTTP_CODE);
        // if($httpCode == 200){
        //     $result_str = $rbody;
        //     printf("result is :\n %s\n", $result_str);
        // }else{
        //     printf("Http error code: %d\n", $httpCode);
        //     printf("Error msg in body: %s\n", $rbody);
        //     printf("header: %s\n", $rheader);
        // }
        $data = json_decode($rbody,true);
        $this->success('',$data);

    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 小程序登录
     * @return void
     */
    public function mini_login()
    {

    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 添加用户
     * @return void
     */
    public function addUser()
    {
        $type = $this->request->post('type');
        $mobile = $this->request->post('mobile');
        $nickname = $this->request->post('nickname');
        $password = $this->request->post('password');
        $divide_rate = $this->request->post('divide_rate');
        $order_auth = $this->request->post('order_auth');
        $data = [
            'type'=>$type,
            'mobile'=>$mobile,
            'nickname'=>$nickname,
            'divide_rate'=>$divide_rate,
            'order_auth'=>$order_auth,
            'parent_id'=>$this->auth->id,
        ];
        if($this->auth->parent_ids){
            $data['parent_ids'] = $this->auth->parent_ids.','.$this->auth->id;
        }else{
            $data['parent_ids'] = $this->auth->id;
        }
        //查询下级总分成比例是否大于100
        $allRate = \app\common\model\User::where('parent_id',$this->auth->id)->sum('divide_rate');
        if($allRate + $divide_rate > 100){
            // $this->error('下级总分成比例不能大于100');
        }
        $ret = $this->auth->register($mobile, $password, '', $mobile, $data);
        if ($ret) {
            $this->success('添加成功');
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 获取自己的用户
     * @return bool
     */
    public function getUserList()
    {
        $where = [];
        $keywords = $this->request->post('keywords');
        $type = $this->request->post('type');
        if($type){
            $where['type'] = $type;
        }
        if($keywords){
            $where['nickname|mobile|user_no'] = ['like', "%{$keywords}%"];
        }
        $where['parent_id'] = $this->auth->id;
//        $list = \app\common\model\User::where($where)
//            ->field('id,nickname,mobile,avatar,createtime,type,divide_rate,order_auth,user_no')
//            ->paginate();
//        $list->each(function($item){
//            $item['createtime'] = date('Y-m-d H:i:s',$item['createtime']);
//            return $item;
//        });
        $list = \app\common\model\User::where($where)
            ->field('id,nickname,mobile,avatar,createtime,type,divide_rate,order_auth,user_no')
            ->select();
        foreach ($list as &$v){
            $v['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
        }
        $this->success('ok',$list);
    }

    /**
     * 修改用户
     * @return void
     */
    public function updateUser()
    {
        $id = $this->request->post('id');
        if(!$id){
            $this->error('参数错误');
        }
        $user = \app\common\model\User::get($id);
        if(!$user){
            $this->error('用户不存在');
        }
        $is_mobile = \app\common\model\User::where('mobile',$this->request->post('mobile'))->where('id','neq',$id)->find();
        if($is_mobile){
            $this->error('手机号已存在');
        }
        $data = [
            'nickname'=>$this->request->post('nickname'),
            'mobile'=>$this->request->post('mobile'),
            'divide_rate'=>$this->request->post('divide_rate'),
        ];
        $password = $this->request->post('password');
        if($password){
            $salt = Random::alnum();
            $newpassword = $this->getEncryptPassword($password, $salt);
            $data['password'] = $newpassword;
            $data['salt'] = $salt;
        }
        $data['updatetime'] = time();
        $res = \app\common\model\User::where('id',$id)->update($data);
        if($res){
            $this->success('修改成功');
        }else{
            $this->error('修改失败');
        }
    }

    /**
     * 用户实名认证
     * @return void
     */
    public function userAuth()
    {
        $card_z = $this->request->post('card_z');
        $card_f = $this->request->post('card_f');
        $realname = $this->request->post('realname');
        $card_no = $this->request->post('card_no');
        $card_start = $this->request->post('card_start');
        $card_end = $this->request->post('card_end');
        if(!$card_z || !$card_f || !$realname || !$card_no || !$card_start || !$card_end){
            $this->error('参数错误');
        }
        $user = \app\common\model\User::get($this->auth->id);
        if($user->is_auth == 1){
            $this->error('请勿重复认证');
        }else{
            $user->realname = $realname;
            $user->card_no = $card_no;
            $user->card_start = $card_start;
            $user->card_end = $card_end;
            $user->card_z = $card_z;
            $user->card_f = $card_f;
            $user->is_auth = 1;
            $user->save();
            $this->success('实名认证成功');
        }
    }

    /**
     * 获取密码加密后的字符串
     * @param string $password 密码
     * @param string $salt     密码盐
     * @return string
     */
    public function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }


    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform",'wechat');
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 提现
     *
     * @ApiMethod (POST)
     * @param string $money  提现金额
     * @param string $account 提现账户
     * @param string $name 真实姓名
     */
    public function withdraw()
    {
        $money = $this->request->post('money');
        $account = $this->request->post('account');
        $name = $this->request->post('name');
        $code = $this->request->post('code');
        $type = 'alipay';

        if ($money <= 0) {
            $this->error('提现金额不正确');
        }
        if ($money > $this->auth->money) {
            $this->error('提现金额超出可提现金额');
        }
        if (!$account) {
            $this->error("提现账户不能为空");
        }
        if (!$name) {
            $this->error("真实姓名不能为空");
        }
        if (!Validate::is($account, "email") && !Validate::is($account, "/^1\d{10}$/")) {
            $this->error("提现账户只能是手机号或Email");
        }

        $ret = Sms::check($this->auth->mobile, $code, 'withdraw');
            if (!$ret) {
                $this->error(__('验证码错误'));
            }

        $config = get_addon_config('withdraw');
        if (isset($config['minmoney']) && $money < 10) {
            $this->error('提现金额不能低于10元');
        }
//        if ($config['monthlimit']) {
            $count = \addons\withdraw\model\Withdraw::where('user_id', $this->auth->id)->whereTime('createtime', 'today')->count();
            if ($count >= 1) {
                $this->error("已达到本日最大可提现次数");
            }
//        }
        Db::startTrans();
        try {
            $handingfee = $money*0.01;
            $data = [
                'orderid' => date("YmdHis") . sprintf("%08d", $this->auth->id) . mt_rand(1000, 9999),
                'user_id' => $this->auth->id,
                'money'   => $money,
                'type'    => $type,
                'account' => $account,
                'handingfee' => $handingfee,
                'name'    => $name,
            ];
            \app\common\model\User::where('id', $this->auth->id)->update(['realname'=>$name,'alipay'=>$account,'updatetime'=>time()]);
            \addons\withdraw\model\Withdraw::create($data);
            \app\common\model\User::money(-$money, $this->auth->id, "提现");
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("提现申请成功！请等待后台审核！");
    }

    /**
     * 提现记录
     * @return string
     */
        public function withdrawlog()
    {
        $withdrawloglist = \addons\withdraw\model\Withdraw::where(['user_id' => $this->auth->id])
            ->order('id desc')
            ->paginate(10)->each(function ($item){
                $item['createtime'] = date('Y-m-d H:i:s',$item['createtime']);
                return $item;
            });
        $this->success('ok',$withdrawloglist);
    }
}
